import os

from django import http
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from django.views import View

from apps.group.models import Shop, ShopComments
from utils.response_code import RETCODE


class GroupView(View):
    def get(self, request):
        shop_id = Shop.objects.filter()
        # 获取用户创建的所有活动
        create_shop = []
        try:
            create_shop = Shop.objects.filter(user=request.user).order_by('create_time')
        except Exception as e:
            return http.HttpResponseBadRequest()
        # dinner设置简介属性
        for shop in create_shop:
            if len(shop.info) > 70:
                shop.shor_discription = shop.info[:70] + '...'
            else:
                shop.shor_discription = shop.info + '...'
        # 修改tag
        context = {
            'user_login': request.user if request.user.is_authenticated() else None,
            'create_shop': create_shop,
            'user': request.user,
        }
        print(context)
        return render(request, 'group.html', context=context)


class GroupSignView(LoginRequiredMixin, View):
    def get(self, request):
        return render(request, 'group_sign.html')

    def post(self, request):
        title = request.POST.get('title')
        info = request.POST.get('info')
        price = request.POST.get('price')
        count = request.POST.get('count')
        receive = request.POST.get('receive')
        end = request.POST.get('end')
        place = request.POST.get('place')
        people = request.POST.get('people')
        image_desctiption = request.POST.get('image_desctiption')
        photo = request.FILES.get("photo")

        db_path = None
        if photo:
            path = os.path.join('.\static', 'upload_images\\' + photo.name)
            print(path)
            db_path = os.path.join('/static' + '/upload_images/' + photo.name)
            if photo.multiple_chunks():
                file_yield = photo.chunks()
                with open(path, 'wb') as f:
                    for buf in file_yield:
                        f.write(buf)
                    else:
                        print('大文件上传完毕')
            else:
                with open(path, 'wb') as f:
                    f.write(photo.read())
                print('小文件上传完毕')

        try:
            Shop.objects.create(
                user=request.user,
                title=title,
                price=price,
                info=info,
                place=place,
                count_least=count,
                count_max=people,
                receive_time=receive,
                end_time=end,
                image_urls=db_path,
                image_description=image_desctiption,
            )
        except Exception as e:
            return http.JsonResponse({'errno': RETCODE.DBERR, 'errmsg': '创建活动失败'})
        return http.JsonResponse({'errno': RETCODE.OK, 'errmsg': '创建活动成功'})


class GroupxqView(View):
    def get(self, request, shop_id):
        try:
            shop = Shop.objects.get(id=shop_id)
        except Shop.DoesNotExist:
            return render(request, '404.html')

        # 获取评论
        comments = []
        try:
            comments = ShopComments.objects.filter(shop=shop).order_by('-create_time')
        except Exception as e:
            print(e)
        # 格式化时间
        for comment in comments:
            comment.create_time = comment.create_time.strftime("%Y-%m-%d %H:%M:%S")
            if comment.parent:
                comment.parent.create_time = comment.parent.create_time.strftime("%Y-%m-%d %H:%M:%S")
        follow_flag = False

        context = {
           'shop': shop,
           'comments': comments,
           'user': request.user,
           'follow_flag': follow_flag,
        }

        return render(request, 'group_xq.html', context)


class CommentsView(LoginRequiredMixin, View):
    def post(self, request, shop_id):
        # 获取评论内容
        comment = request.POST.get('comment')
        parent_id = request.POST.get('parent_id')
        print(comment)
        # 获取dinner对象
        try:
            shop = Shop.objects.get(id=shop_id)
        except Shop.DoesNotExist:
            return http.HttpResponseBadRequest()
        # 获取user对象
        user = request.user
        # 保存到数据库
        try:
            dinner_comment = ShopComments.objects.create(
                shop=shop,
                user=user,
                content=comment
            )
            if parent_id:
                dinner_comment.parent = ShopComments.objects.get(id=parent_id)
        except Exception as e:
            print(e)
            return http.JsonResponse({'errno': RETCODE.DBERR, 'errmsg': '评论失败'})
        return http.JsonResponse({'errno': RETCODE.OK, 'errmsg': '评论成功'})


